"""
删除序列相同元素并保持顺序

问题：
    怎样在一个序列上面保持元素顺序的同时消除重复的值？
解决方案：
    如果序列上的值都是 hashable 类型，那么可以很简单的利用集合或者生成器来解决这个问题
"""


def dedupe(items, key=None):
    seen = set()
    for item in items:
        val = item if key is None else key(item)
        if val not in seen:
            yield item
            seen.add(val)


def use_dedupe():
    company_list = ["Netflix", "Apple", "SpaceX", "Google", "Apple", "Amazon"]
    print(list(dedupe(company_list)))
    # 输出结果：
    """
    ['Netflix', 'Apple', 'SpaceX', 'Google', 'Amazon']
    """

    company_list = [
        {
            "code": "APPL",
            "name": "Apple"
        },
        {
            "code": "GOOG",
            "name": "Google"
        },
        {
            "code": "APPL",
            "name": "Apple"
        },
    ]
    print(list(dedupe(company_list, lambda d: (d['code'], d['name']))))
    # 输出结果：
    """
    [{'code': 'APPL', 'name': 'Apple'}, {'code': 'GOOG', 'name': 'Google'}]
    """


if __name__ == '__main__':
    use_dedupe()
